<template>
  <el-dialog
      @close="handleDialogClose"
      destroy-on-close
    :title="headerTitle"
    :close-on-click-modal="false"
    :visible="detailsVisible"
    width="470px"
  >
    <el-form
      ref="form"
      :model="form"
      label-width="120px"
      inline
      label-position="right"
      class="form-container"
      :rules="rules"
    >
      <el-form-item label="班次名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="上班时间" prop="time0">
        <el-time-picker
            :picker-options="pickerOptions"
            value-format="HH:mm"
            v-model="form.time0"
            placeholder="上班时间">
        </el-time-picker>
<!--        <el-input v-model="form.name"></el-input>-->
      </el-form-item>
      <el-form-item label="下班时间" prop="time1">
        <el-time-picker
            :picker-options="pickerOptions"
            value-format="HH:mm"
            v-model="form.time1"
            placeholder="下班时间">
        </el-time-picker>
      </el-form-item>
      <el-form-item label="上班打卡规则" prop="timeSpanOfBeLater">
        晚于<el-input v-model="form.timeSpanOfBeLater" style="width: 86px; margin: 0px 8px"></el-input>分钟打卡记为迟到
      </el-form-item>
      <el-form-item label=" " prop="timeSpanOfTime0Miss">
        晚于<el-input v-model="form.timeSpanOfTime0Miss" style="width: 86px; margin: 0px 8px"></el-input>分钟打卡记为半天缺卡
      </el-form-item>
      <el-form-item label="下班打卡规则" prop="timeSpanOfLeaveEarly">
        早于<el-input v-model="form.timeSpanOfLeaveEarly" style="width: 86px; margin: 0px 8px"></el-input>分钟打卡记为早退
      </el-form-item>
      <el-form-item label=" " prop="timeSpanOfTime1Miss">
        早于<el-input v-model="form.timeSpanOfTime1Miss" style="width: 86px; margin: 0px 8px"></el-input>分钟打卡记为半天缺卡
      </el-form-item>
      <el-form-item label="班次说明" prop="description">
        <el-input type="textarea" v-model="form.description"></el-input>
      </el-form-item>
    </el-form>
    <section style="text-align: center;">
        <el-button size="small" @click="handleDialogClose">取消</el-button>
        <el-button size="small" type="primary" :loading="saveLoading" @click="hanldeConfirm">确定</el-button>
    </section>
  </el-dialog>
</template>
<script>
import {workingscheduleCreate, workingscheduleUpdate} from "@/api/pcmj/bcgl";

export default {
  data() {
    var validateName = (rule, value, callback) => {
      if (value == '') {
        // 请输入班次名称
        callback(new Error('请输入班次名称'));
      } else {
        callback();
      }
    };

    var validateTimeSpanOfBeLater = (rule, value, callback) => {
      console.log(77, this.form);
      let self = this.form;
      if (isNaN(value)) {
        callback("只能输入数字");
      } else if(value<0||value>60*24){
        callback("只能0~"+60*24+"之间的数字");
      } else {
        if (rule.field == 'timeSpanOfBeLater' && self.timeSpanOfTime0Miss) {
          if (value >= 0 && self.timeSpanOfTime0Miss*1 >= 0 && value >= self.timeSpanOfTime0Miss*1) {
            callback(new Error("上班缺卡时间必须大于上班迟到时间"));
          } else  {
            callback()
          }
        } else if (rule.field == 'timeSpanOfTime0Miss' && self.timeSpanOfBeLater) {
          if (value >= 0 && self.timeSpanOfBeLater*1 >= 0 && value*1 <= self.timeSpanOfBeLater*1) {
            callback(new Error("上班缺卡时间必须大于上班迟到时间"));
          } else  {
            callback()
          }
        } else if (rule.field == 'timeSpanOfLeaveEarly' && self.timeSpanOfTime1Miss) {
          if (value >= 0 && self.timeSpanOfTime1Miss*1 >= 0 && value*1 >= self.timeSpanOfTime1Miss*1) {
            callback(new Error("下班缺卡时间必须大于下班早退时间"));
          } else  {
            callback()
          }
        } else if (rule.field == 'timeSpanOfTime1Miss' && self.timeSpanOfLeaveEarly) {
          if (value >= 0 && self.timeSpanOfLeaveEarly*1 >= 0 && value*1 <= self.timeSpanOfLeaveEarly*1) {
            callback(new Error("下班缺卡时间必须大于下班早退时间"));
          } else  {
            callback()
          }
        } else  {
          callback()
        }
      }
    };
    return {
      pickerOptions: {
        format: 'HH:mm', // 格式化时间显示
        selectableRange:null // 设置可选时间范围
      },
      rules: {
        name: [
          {validator: validateName, required: true, trigger: 'blur'},
          {max: 24, message: '长度最大 24 个字符', trigger: 'blur' }
        ],
        time0: [
          {message: "请选择上班时间", required: true, trigger: 'blur'},
          { validator: (rule, value, callback) => {
              console.log(100, value, this.form.time1);
              if (value.length > 0 && this.form.time1?.length > 0) {
                if (this.timeChange(value) > this.timeChange(this.form.time1)) {
                  callback(new Error('下班时间不能比上班时间早'))
                } else {
                  callback()
                }
              }
            }, trigger: 'blur'
          }
        ],
        time1: [
          {message: "请选择下班时间", required: true, trigger: 'blur'},
          { validator: (rule, value, callback) => {
              console.log(112, value, this.form.time0);
              if (value.length > 0 && this.form.time0?.length > 0) {
                if (this.timeChange(value) < this.timeChange(this.form.time0)) {
                  callback(new Error('下班时间不能比上班时间早'))
                } else {
                  callback()
                }
              }
            }, trigger: 'blur'
          }
        ],
        timeSpanOfBeLater: [
          {message: "不能为空", required: true, trigger: 'blur'},
          { validator: validateTimeSpanOfBeLater,required: true, trigger: 'blur'},
        ],
        timeSpanOfTime0Miss: [
          {message: "不能为空", required: true, trigger: 'blur'},
          { validator: validateTimeSpanOfBeLater,required: true, trigger: 'blur'},
        ],
        timeSpanOfLeaveEarly: [
          {message: "不能为空", required: true, trigger: 'blur'},
          { validator: validateTimeSpanOfBeLater,required: true, trigger: 'blur'},
        ],
        timeSpanOfTime1Miss: [
          {message: "不能为空", required: true, trigger: 'blur'},
          { validator: validateTimeSpanOfBeLater,required: true, trigger: 'blur'},
        ],
        description: [
          {max: 100,  message: "输入长度在1~100个字符", trigger: 'blur'},
        ],
      },
      saveLoading:false,
      form: {
        name: "",
        creatorId:"",
        description:"",
        time0:null,
        time1:null,
        timeSpanOfBeLater:"",
        timeSpanOfTime0Miss:"",
        timeSpanOfLeaveEarly:"",
        timeSpanOfTime1Miss:"",
      },
    };
  },
  props: {
    detailsVisible: {
      type: Boolean,
      default: false
    },
    handleType: {
      type: String,
      default: "add",
    },
    tableRow:{
      type: Object,
      default: ()=>{
        return {}
      },
    }
  },
  computed: {
    headerTitle() {
      return this.handleType=='edit'? this.i18n.t('Modified classes') : this.i18n.t('New classes');
    },
  },
  watch: {},
  methods: {
    timeChange(str) {
      let arr = str.split(':');
      return arr[0]*3600 + arr[1]*60;
    },
    workingscheduleUpdate(params){
      this.saveLoading=true
      workingscheduleUpdate(params).then(res=>{
        if (res.code == 200) {
          // 修改成功
          this.W.$tips("success", this.i18n.t('Modified successfully!'));
          // 更新父页面表格
          this.$parent.getList()
          this.handleDialogClose()
        }
      }).catch().finally(()=>{
        this.saveLoading=false
      })
    },
    // 时分秒转分钟
    hmsToMinute(time){
      if (!time) {
        return 0
      }
      var timeList=time.split(":")
      if (timeList[0]=='00'){
        return parseInt(timeList[1])
      }else{
        return parseInt(timeList[0]*60)+parseInt(timeList[1])
      }

      // var hour=Math.floor(time/60)
      // if (hour<10){
      //   hour="0"+hour
      // }
      // var innerMinute=time % 60;
      // if (innerMinute<10){
      //   innerMinute="0"+innerMinute
      // }
      // return `${hour}:${innerMinute}:00`
    },
    // 分钟转时分秒
    minuteToHour(minute){
      if (!minute) {
        return "00:00:00"
      }
      var hour=Math.floor(minute/60)
      if (hour<10){
        hour="0"+hour
      }
      var innerMinute=minute % 60;
      if (innerMinute<10){
        innerMinute="0"+innerMinute
      }
      return `${hour}:${innerMinute}:00`
    },
    handleDialogClose() {
      // 关闭dialog时，清空表单数据
      this.$refs.form.resetFields();
      if (this.handleType=='add'||this.handleType=='edit'){
        this.$parent.detailsVisible=false
      }else{
        // 关闭添加弹窗
        this.$parent.classesDetailsVisible=false
      }
    },
    workingscheduleCreate(params){
      this.saveLoading=true
      console.log('参数',params);
      workingscheduleCreate(params).then(res => {
        if (res.code == 200) {
          // 添加成功
          this.W.$tips("success", this.i18n.t('Add successfully!'));
          // 添加特殊节日弹窗界面
          if (this.handleType=='addSpecial'){
            // 刷新班次下拉列表
            this.$parent.workingscheduleGetlist()
          }else{
            // 更新父页面表格
            this.$parent.getList()
          }
          // 关闭添加弹窗
          this.handleDialogClose()
        }
      }).catch().finally(()=>{
        this.saveLoading=false
      })
    },
    hanldeConfirm(){
      // console.log(123, this.form);
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log('下一步',this.form);
          var params=JSON.parse(JSON.stringify(this.form))
          console.log(JSON.parse(localStorage.getItem("userInfo")));
          params.creatorId=JSON.parse(localStorage.getItem("userInfo")).userId
          params.timeSpanOfBeLater=this.minuteToHour(params.timeSpanOfBeLater)
          params.timeSpanOfTime0Miss=this.minuteToHour(params.timeSpanOfTime0Miss)
          params.timeSpanOfLeaveEarly=this.minuteToHour(params.timeSpanOfLeaveEarly)
          params.timeSpanOfTime1Miss=this.minuteToHour(params.timeSpanOfTime1Miss)
          if (this.handleType=='add'||this.handleType=='addSpecial'){
            params.time0+=":00"
            params.time1+=":00"
          }else{
            var time0List=params.time0.split(":")
            var time1List=params.time1.split(":")
            if (time0List.length==2){
              params.time0+=":00"
            }
            if (time0List.length==3){
              // params.time0+=":00"
              time0List[2]="00"
              params.time0=time0List.join(":")
            }

            if (time1List.length==2){
              params.time1+=":00"
            }
            if (time1List.length==3){
              // params.time0+=":00"
              time1List[2]="00"
              params.time1=time1List.join(":")
            }

            params.createBy=params.accountInfo.userName
            delete params.loading
          }

          // delete params.isDefault
          // delete params.id

          console.log(params);
          if (this.handleType=='edit'){
            this.workingscheduleUpdate(params)
          }else{
            this.workingscheduleCreate(params)
          }

          // 更新父页面表格
          // console.log(this.$parent.$parent);
        } else {
          return false;
        }
      })
    },
  },
  mounted(){
    // debugger
    if (this.handleType=='edit'){
      this.form=JSON.parse(JSON.stringify(this.tableRow))
      this.form.timeSpanOfBeLater=this.hmsToMinute(this.form.timeSpanOfBeLater)
      this.form.timeSpanOfTime0Miss=this.hmsToMinute(this.form.timeSpanOfTime0Miss)
      this.form.timeSpanOfLeaveEarly=this.hmsToMinute(this.form.timeSpanOfLeaveEarly)
      this.form.timeSpanOfTime1Miss=this.hmsToMinute(this.form.timeSpanOfTime1Miss)
      console.log(this.form);
    }
  }
};
</script>
<style scoped lang="scss">
::v-deep.form-container {
  .el-form-item {
    display: inline-flex;
    .el-form-item__label {
      width: 115px !important;
    }
    .el-input {
      width: 260px;
    }
  }
}
</style>
